package com.gx.smart.construction.ui.house.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.databinding.DataBindingUtil;
import androidx.navigation.Navigation;

import com.blankj.utilcode.util.ToastUtils;
import com.gx.smart.construction.R;
import com.gx.smart.construction.databinding.SmartHomeFragmentBinding;
import com.gx.smart.construction.ui.common.db.ConstructionDatabase;
import com.gx.smart.construction.ui.common.fragment.CommonSelectRoomFragment;
import com.gx.smart.construction.ui.common.model.RoomName;
import com.gx.smart.construction.ui.common.model.UnitName;
import com.gx.smart.construction.ui.common.page.SearchRoomActivity;
import com.gx.smart.construction.ui.house.viewmodel.SmartHomeViewModel;
import com.gx.smart.lib.event.LoadingMessageEvent;
import com.mylhyl.circledialog.CircleDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.EventBus;

public class SmartHomeFragment extends CommonSelectRoomFragment<SmartHomeViewModel> implements View.OnClickListener {

    @Override
    public int onBindLayout() {
        return R.layout.smart_home_fragment;
    }

    @Override
    public String getToolbarTitle() {
        return "智能家居";
    }

    @Override
    protected Class<SmartHomeViewModel> onBindViewModel() {
        return SmartHomeViewModel.class;
    }

    @Override
    public int getRightImage() {
        return R.mipmap.ic_smart_home_record;
    }

    @Override
    public void initContentView(ViewGroup root) {
        SmartHomeFragmentBinding binding = DataBindingUtil.inflate(getLayoutInflater(), onBindLayout(), root, true);
        binding.setLifecycleOwner(getViewLifecycleOwner());
        binding.setSmartHomeFragment(this);
        binding.setSelectRoomViewModel(viewModel);
        mRightImage.setOnClickListener(this);
    }


    @Override
    protected void initData() {
        viewModel.getProgress();
    }

    @SuppressWarnings("unused")
    public void selectArea(View v) {
        selectArea();
    }

    @SuppressWarnings("unused")
    public void selectBuilding(View v) {
        selectBuilding();
    }

    @SuppressWarnings("unused")
    public void selectUnit(View v) {
        selectUnit();
    }

    @Override
    protected void initObserver() {
        viewModel.error.observe(getViewLifecycleOwner(), result -> {
            if (result) {
                EventBus.getDefault().post(new LoadingMessageEvent(false));
            }
        });
    }

    @SuppressLint({"RestrictedApi", "NonConstantResourceId"})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rightImageView) {
//            Navigation.findNavController(v).navigate(R.id.action_smartHomeFragment_to_smartHomeRecordFragment);
//            Navigation.findNavController(v).navigate(R.id.action_smartHomeFragment_to_smartHomeRecordFragmentV2);
//            Navigation.findNavController(v).navigate(R.id.action_smartHomeFragment_to_smartHomeRecordFragmentV3);
            Navigation.findNavController(v).navigate(R.id.action_smartHomeFragment_to_smartHomeRecordFragmentV4);
        }
    }

    //选择房间跳转页面
    private final ActivityResultLauncher<Intent> roomSearchLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
        int resultCode = result.getResultCode();
        if (resultCode == Activity.RESULT_OK) {
            Intent data = result.getData();
            if (data != null) {
                String number = data.getStringExtra("number");
                String id = data.getStringExtra("id");
                RoomName roomName = new RoomName();
                roomName.setContent(number);
                roomName.setId(id);
                viewModel.changeRoomName(roomName);
                viewModel.getWayGateDevice(id).observe(getViewLifecycleOwner(), sn -> {
                    EventBus.getDefault().post(new LoadingMessageEvent(false));
                    viewModel.changeSn(sn);
                });
            }

        }
    });

    @SuppressWarnings({"unused"})
    public void selectRoom(View v) {
        UnitName unitName = viewModel.getUnitName().getValue();
        if (unitName == null) {
            ToastUtils.showLong("请先选择单元");
            return;
        }
        Intent intent = new Intent(requireActivity(), SearchRoomActivity.class);
        intent.putExtra("parentId", unitName.getId());
        roomSearchLauncher.launch(intent);
    }


    @SuppressWarnings("unused")
    public void addGateWay(View v) {
        if (commonHandle()) {
            if (AndPermission.hasPermissions(requireActivity(), Permission.CAMERA)) {
                // Storage permission are allowed.
                Intent intent = new Intent(requireActivity(), CaptureActivity.class);
                scanQRCode.launch(intent);
                return;
            }

            AndPermission.with(this)
                    .runtime()
                    .permission(Permission.CAMERA)
                    .onGranted(permissions -> addGateWay(v))
                    .onDenied(permissions -> {
                        // Storage permission are not allowed.
                        new CircleDialog.Builder()
                                .setTitle("获取权限")
                                .setText("请允许获取对应的权限，否则不能运行？")
                                .setPositive("确定", null)
                                .show(requireActivity().getSupportFragmentManager());
                    })
                    .start();
        }
    }

    ActivityResultLauncher<Intent> scanQRCode = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        String sn = data.getStringExtra(Constant.CODED_CONTENT);
                        new CircleDialog.Builder()
                                .setTitle("添加网关")
                                .setText(sn)
                                .setPositive("确定", v -> addGateWayAction(sn))
                                .setNegative("取消", null)
                                .show(requireActivity().getSupportFragmentManager());
                    }
                }
            });

    @SuppressWarnings("null")
    private void addGateWayAction(String sn) {
        EventBus.getDefault().post(new LoadingMessageEvent(true));
        RoomName roomName = viewModel.getRoomName().getValue();
        if (roomName != null) {
            viewModel.addWayGate(roomName.getId(), sn)
                    .observe(getViewLifecycleOwner(), success -> {
                        if (success) {
                            EventBus.getDefault().post(new LoadingMessageEvent(false));
                            viewModel.changeSn(sn);
                        }
                    });
        }

    }

    @SuppressWarnings({"unused"})
    public void deleteGateWay(View v) {
        if (commonHandle()) {
            if (TextUtils.isEmpty(viewModel.getSn().getValue())) {
                ToastUtils.showLong("当前房屋没有绑定设备");
                return;
            }
            EventBus.getDefault().post(new LoadingMessageEvent(true));
            RoomName roomName = viewModel.getRoomName().getValue();
            if (roomName != null) {
                viewModel.deleteWayGate(roomName.getId())
                        .observe(getViewLifecycleOwner(), success -> {
                            EventBus.getDefault().post(new LoadingMessageEvent(false));
                            viewModel.changeSn("");
                        });
            }
        }
    }
}